package cn.daniellee.plugin.ce.listener;

import cn.daniellee.plugin.ce.CraftEconomy;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteStreams;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.messaging.PluginMessageListener;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;

public class BungeeListener implements PluginMessageListener {

	@Override
	public void onPluginMessageReceived(String s, Player player, byte[] bytes) {
		ByteArrayDataInput in = ByteStreams.newDataInput(bytes);
		String subChannel = in.readUTF();
		// 接收更新消息
		if ("CraftEconomy".equals(subChannel)) {
			short length = in.readShort();
			byte[] msgBytes = new byte[length];
			in.readFully(msgBytes);
			DataInputStream msgIn = new DataInputStream(new ByteArrayInputStream(msgBytes));
			try {
				String operation = msgIn.readUTF();
				if ("Update".equals(operation)) {
					String name = msgIn.readUTF();
					CraftEconomy.getInstance().getStorage().refreshPlayerData(name);
					Player targetPlayer = Bukkit.getPlayer(name);
					double amount;
					if (targetPlayer != null && (amount = msgIn.readDouble())  != 0) {
						if (amount > 0) targetPlayer.sendMessage((CraftEconomy.getInstance().getPrefix() + CraftEconomy.getInstance().getConfig().getString("message.bungee-deposit", "&eYou spent &6{money}").replace("{money}", CraftEconomy.getInstance().getFormat().format(amount))).replace("&", "§"));
						else targetPlayer.sendMessage((CraftEconomy.getInstance().getPrefix() + CraftEconomy.getInstance().getConfig().getString("message.bungee-withdraw", "&eYou received &6{money}").replace("{money}", CraftEconomy.getInstance().getFormat().format(amount))).replace("&", "§"));
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
